<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
  <head>
    <title>编辑转换自采购订单的入库单</title>
    <script type="text/javascript">
      Ext.onReady(function(){
        //你要引用的订单类型
        var warehousingEntryId = new Ext.form.Hidden({
          name: 'id',
          value:<%=params[:id]%>
        });

        var purchaseOrderId = new Ext.form.Hidden({
          name: 'purchase_order_id'
        });
        
        //备注
        var desc = new Ext.form.TextField({
          fieldLabel: '备注',
          name: 'description',
          anchor: '90%'
        });

        //所有供应商
        var fromVendor = new Ext.form.TextField({
          fieldLabel: '供应商',
          name: 'vendor_name',
          anchor: '90%',
          readOnly:true
        });
        
        //选供应商ID
        var vendorId = new Ext.form.Hidden({
          name: 'vendor_id'
        });
        
        //所有仓库
        var warehouseTemplate = new Ext.XTemplate('<tpl for="."><div class="search-item">', '{number}|{name}', '</div></tpl>');
        var warehouseStore = new Ext.data.Store({
          proxy: new Ext.data.HttpProxy({
            url: "/warehouse/getAllWarehouse?for_cbb=true"
          }),
          reader: new Ext.data.JsonReader({
            root: 'root'
          }, [{
              name: 'id'
            },{
              name: 'number'
            }, {
              name: 'name'
            }])
        });

        var toWarehouse = new Ext.form.ComboBox({
          store: warehouseStore,
          fieldLabel: '到仓库',
          allowBlank: false,
          blankText: "仓库必须选择",
          emptyText: '请选择...',
          valueField: 'id',
          displayField: 'name',
          hiddenName: 'warehouse_id',
          //typeAhead: false,
          loadingText: '搜索中...',
          anchor: '90%',
          //pageSize: 10,
          //hideTrigger: false,
          tpl: warehouseTemplate,
          minChars: 0,
          itemSelector: 'div.search-item',
          triggerAction: 'all',
          editable:false,
          selectOnFocus:true
        });

        //入库日期
        var actionDate = new Ext.form.DateField({
          fieldLabel: '入库日期',
          name: 'action_date',
          format: 'Y-m-d', //格式化日期
          //disabledDays: [0,6],	//不让选择周六，周日
          //disabledDaysText: "周末要休息",
          invalidText: "您输入的日期格式不对，正确格式为2010-01-18",
          allowBlank: false,
          blankText: "入库日期必须选择",
          emptyText: '请选择日期...'
          //anchor: '50%'
        });
        //--------------------------------------------------------------------------
        //销售订单单号combobox
        var saleOrderNumberTemplate = new Ext.XTemplate('<tpl for="."><div  class="search-item"><div style="float:left; width:150px">{order_number}</div><div>', '{is_suit}', '</div></div></tpl>');
        var saleOrderNumberStore = new Ext.data.Store({
          proxy: new Ext.data.HttpProxy({
            url: "/purchase_order/getSaleOrdersOfPurchaseById"
          }),
          reader: new Ext.data.JsonReader({
            totalProperty: 'totalProperty',
            root: 'root'
          }, [{
              name: 'id'
            }, {
              name: 'sale_order_id'
            }, {
              name: 'order_number',
              mapping:'sale_order.order_number'
            }])
        });
        //销售订单CBB
        var saleOrderNumberCBB = new Ext.form.ComboBox({
          store: saleOrderNumberStore,
          fieldLabel: '销售订单单号',
          allowBlank: false,
          blankText: "销售订单必须选择",
          emptyText: '请选择...',
          //valueField: 'sale_order_id',
          //hiddenName: 'sale_order_id',
          displayField: 'order_number',          
          hideTrigger:false,
          //typeAhead: false,
          loadingText: '搜索中...',
          anchor: '90%',
          //hideTrigger: false,
          triggerAction: 'all',
          tpl: saleOrderNumberTemplate,
          minChars: 0,
          itemSelector: 'div.search-item',
          selectOnFocus:true
        });

        saleOrderNumberCBB.on('select', function(combo, record, index) {
          var purchaseOrderItemRecord = purchaseDetailsSM.getSelected();
          if (!purchaseOrderItemRecord) {
            return false;
          }
          purchaseOrderItemRecord.set('sale_order_id',record.get('sale_order_id'));
          purchaseOrderItemRecord.set('sale_order_number',record.get('order_number'));
        });
        
        //入库Grid Store
        var purchaseDetailsDS = new Ext.data.Store({
          baseParams:{id:warehousingEntryId.getValue()},
          proxy: new Ext.data.HttpProxy({
            url: '/warehousing_entry/getDetailsBalanceByIdForEntry'
          }),
          reader: new Ext.data.JsonReader({
            totalProperty: 'totalProperty',
            root: 'root'
          }, [{
              name: 'id'
            },{
              name: 'sale_order_number'
            },{
              name: 'sale_order_id'
            },{
              name: 'sale_order_detail_id'
            },{
              name: 'number'
            },{
              name: 'spec'
            },{
              name: 'product_name'
            },{
              name: 'unit'
            },{
              name: 'quantity',
              mapping:'balance_quantity',
              type: 'int'
            },{
              name: 'ori_quantity',
              mapping:'balance_quantity',
              type: 'int'
            },{
              name: 'product_id'
            },{
              name: 'description'
            },{
              name: 'amount',
              type: 'float'
            }])
        });

        //生成产品Grid的CM
        var purchaseDetailsSM = new Ext.grid.CheckboxSelectionModel({singleSelect:true});
        var purchaseDetailsCM = new Ext.grid.ColumnModel({defaults: {
            sortable: true,
            menuDisabled: false
          },columns:[new Ext.grid.RowNumberer(),purchaseDetailsSM,{
              id: 'common',
              header: 'DB',
              dataIndex: 'id',
              width: 50
            },{
              header: '销售订单ID',
              dataIndex: 'sale_order_id',
              width: 50,
              hidden: true
            },{
              header: '销售订单单号',
              dataIndex: 'sale_order_number',
              editor:saleOrderNumberCBB,
              width: 170
            },{
              header: '产品名称',
              dataIndex: 'product_name',
              width: 210
            },{
              header: '产品ID',
              dataIndex: 'product_id',
              width: 50,
              hidden: false
            },{
              header: '产品编号',
              dataIndex: 'number',
              width: 95
            },{
              header: '规格',
              dataIndex: 'spec',
              width: 50
            },{
              header: '单位',
              dataIndex: 'unit',
              width: 50
            },{
              header: '数量',
              dataIndex: 'quantity',
              align: 'right',
              editor: new Ext.form.NumberField({
                allowBlank: false,
                allowDecimals: false,
                allowNegative: false
              }),
              width: 50
            },{
              header: '备注',
              dataIndex: 'description',
              width: 130,
              editor:new Ext.form.TextField({
                name: 'description',
                anchor: '90%'
              })
            }
          ]});

        //采购订单的产品的Grid
        var purchaseDetailsGrid = new Ext.grid.EditorGridPanel({
          store: purchaseDetailsDS,
          cm: purchaseDetailsCM,
          sm: purchaseDetailsSM,
          width: 900,
          height: 350,
          //frame: true,
          //title: '进货品种列表',
          //frame: true,
          //plugins: checkColumn,
          clicksToEdit: 1,//这里应该是单击就可以修改的意思。因为默认是要双击的。
          tbar: [{
              text: '添加产品',
              iconCls: 'addItem',
              disabled: true,
              handler : function(){
                // access the Record constructor through the grid's store
                var Product = purchaseDetailsGrid.getStore().recordType;
                var productRecord = new Product({
                  product_name: '请选择产品'
                });
                purchaseDetailsGrid.stopEditing();
                purchaseDetailsDS.insert(0, productRecord);
                purchaseDetailsGrid.startEditing(0, 0);
              }
            },{
              text: '删除',
              iconCls: 'remove',
              handler : function(){
                var record = purchaseDetailsSM.getSelected();
                if (!record) {
                  return false;
                }
                purchaseDetailsDS.remove(record);
              }
            }]
        });

        //暂时保存按钮
        var submitButton = new Ext.Button({
          text: '提交',
          iconCls: 'icon-save',
          handler: function(){
            //saveWarehousingEntry("save");
            if(entryForPurchaseFormPanel.form.isValid()){              
              var productsJsonStr = gridStoreToJson(purchaseDetailsDS,rejectKeyArray);
              if (productsJsonStr === ""){
                Ext.MessageBox.show({
                  title: '提示',
                  msg: "您还没有选择有效的产品或选择的产品数量为0！",
                  buttons: Ext.MessageBox.OK,
                  icon: Ext.MessageBox.INFO
                });
                return;
              }
              this.disable();
              var allJsonStr = entryForPurchaseFormPanel.getForm().getValues();
              allJsonStr = Ext.util.JSON.encode(allJsonStr);
              allJsonStr = Ext.util.Format.substr(allJsonStr,0,allJsonStr.length-1);
              allJsonStr = allJsonStr + ",\"products\":" + productsJsonStr + "}";
              //alert(allJsonStr);
              Ext.Ajax.request({
                url : '/warehousing_entry/transformPurchaseIntoEntry',
                success : function (result, request) {
                  //Ext.MessageBox.alert("提示","提交成功");
                  editWarehousingEntryOrderWin.destroy();
                },
                failure : function (result, request){
                  Ext.MessageBox.show({
                    title: '消息',
                    msg: "通讯失败，请从新操作",
                    buttons: Ext.MessageBox.OK,
                    icon: Ext.MessageBox.WARNING
                  });
                  editWarehousingEntryOrderWin.destroy();
                },
                method : 'POST',
                params : {
                  data : Ext.util.JSON.encode(allJsonStr),
                  authenticity_token: authToken.getValue()
                }
              });
            }
          }
        });

        //
        var closeButton = new Ext.Button({
          text: '关闭',
          tooltip: '关闭当前窗口，并且当前编辑的信息不能保存。',
          iconCls: 'exit',
          handler: function(){
            editWarehousingEntryOrderWin.destroy();
          }
        });
        
        var entryForPurchaseFormPanel = new Ext.form.FormPanel({
          //baseCls: 'x-plain',
          //renderTo: 'entry_form',
          labelWidth: 55,
          width: '900',
          labelAlign: 'right',
          frame : true,
          url : '/delivery_order/update',
          method: 'GET',
          reader: new Ext.data.JsonReader({
            root: 'root'
          }, [{
              name: 'id'
            }, {
              name: 'vendor_name',
              mapping: 'vendor.name'
            }, {
              name: 'warehouse_id'
            }, {
              name: 'purchase_order_id'
            }, {
              name: 'action_date',
              type: 'date',
              dateFormat: 'Y/m/d'
            }, {
              name: 'description'
            }]),
          items: [{
              layout: 'column',
              border: false,
              items: [{
                  columnWidth: .4,
                  layout: 'form',
                  border: false,
                  items: [fromVendor]
                }, {
                  columnWidth: .3,
                  layout: 'form',
                  border: false,
                  items: [toWarehouse]
                }, {
                  columnWidth: .3,
                  layout: 'form',
                  border: false,
                  items: [actionDate]
                }]
            },{
              layout: 'column',
              border: false,
              items: [{
                  columnWidth: 1,
                  layout: 'form',
                  border: false,
                  items: [desc]
                }]
            },{
              layout: 'column',
              border: false,
              items: [{
                  columnWidth: 1,
                  layout: 'form',
                  border: false,
                  items: [purchaseDetailsGrid]
                }]
            },vendorId,warehousingEntryId,purchaseOrderId],
          buttons: [submitButton,closeButton]
        });
        
        entryForPurchaseFormPanel.render('entry_form');
        //
        purchaseDetailsDS.load();
        purchaseDetailsGrid.on('afteredit', afterEdit, this );

        function afterEdit(obj) {
          
          if(obj.field=="quantity"){
            if (obj.record.get('quantity') > obj.record.get('ori_quantity') || obj.record.get('quantity')  == 0){
              obj.record.set('quantity', obj.record.get('ori_quantity'));
              return;
            }
          }
          
          if(obj.field=="quantity"||obj.field=="unit_price"){
            if(obj.record.get('quantity')>0&&obj.record.get('unit_price')){
              obj.record.set('amount',obj.record.get('quantity')*100*obj.record.get('unit_price')/100);
            }
          }
        }

        warehouseStore.load({callback: function(record, options, success){
            if(success){
              entryForPurchaseFormPanel.form.load({
                url: '/warehousing_entry/getWarehousingEntryById?id=' + <%=params[:id]%>,
                method : 'GET',
                waitMsg: '正在载入数据...',
                success: function(form, action){
                  saleOrderNumberStore.baseParams.id = purchaseOrderId.getValue();
                },
                failure: function(form, action){
                  Ext.MessageBox.alert('提示信息', '信息加载失败');
                }
              });
            }else{
              Ext.Msg.alert('操作','失败！');
            }
          }});

      })
    </script>
  </head>
  <body>
    <div id="entry_form"></div>
  </body>
</html>
